package cn.yuxiaoyuan.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.IdUtil;
import cn.yuxiaoyuan.constants.RedisCacheConstants;
import cn.yuxiaoyuan.feign.LoginFeignApi;
import cn.yuxiaoyuan.pojo.domain.Driver;
import cn.yuxiaoyuan.mapper.DriverMapper;
import cn.yuxiaoyuan.pojo.domain.DriverSetting;
import cn.yuxiaoyuan.pojo.dto.LoginDto;
import cn.yuxiaoyuan.pojo.ro.PointRo;
import cn.yuxiaoyuan.result.JSONResult;
import cn.yuxiaoyuan.service.IDriverService;
import cn.yuxiaoyuan.service.IDriverSettingService;
import cn.yuxiaoyuan.template.BitStatesUtils;
import cn.yuxiaoyuan.template.NameUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 司机对象 服务实现类
 * </p>
 *
 * @author whale
 * @since 2025-06-12
 */
@Service
public class DriverServiceImpl extends ServiceImpl<DriverMapper, Driver> implements IDriverService {
    @Autowired
    private LoginFeignApi loginFeignApi;
    @Autowired
    private IDriverSettingService driverSettingService;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Override
//    @GlobalTransactional(name = "driver-wechat-register",rollbackFor = Exception.class)
    public JSONResult register(String code, String openid,String phone) {
        //保存数据库的操作
        Driver one = this.getOne(new LambdaQueryWrapper<Driver>()
                .eq(Driver::getOpenId, openid)
                .or()
                .eq(Driver::getPhone, phone));
        if(one == null){//证明没有这个用户
            Driver driver = buildDriver(openid,phone);
            saveUaaLogin(driver);
            //初始化其他表的默认数据
            return JSONResult.success("注册成功");
        }else {
            return JSONResult.error("该手机好已经被注册:"+phone);
        }
    }

    @Override
    public JSONResult getDriverState() {
        long loginIdAsLong = StpUtil.getLoginIdAsLong();
        Driver byId = this.getById(loginIdAsLong);
        Long bitState = byId.getBitState();
        boolean b = BitStatesUtils.hasState(bitState, BitStatesUtils.OP_REAL_AUTHENTICATIONED);
        return JSONResult.success(b);
    }

    @Override
    public JSONResult driverOnline() {
        //得到当前登录的司机的id
        long loginIdAsLong = StpUtil.getLoginIdAsLong();
        //查询司机的接单配置
        DriverSetting byId = driverSettingService.getById(loginIdAsLong);
        if(byId != null){
            //key  value  时间  单位
            redisTemplate.opsForValue().set(RedisCacheConstants.DRIVER_ONLINE_KEY+loginIdAsLong,
                    byId,5, TimeUnit.MINUTES
            );
           return JSONResult.success();
        }
        return JSONResult.error("请先设置接单配置");
    }

    @Override
    public JSONResult driverOffline() {
        long loginIdAsLong = StpUtil.getLoginIdAsLong();
        redisTemplate.delete(RedisCacheConstants.DRIVER_ONLINE_KEY+loginIdAsLong);
        return  JSONResult.success();
    }

    @Override
    public JSONResult locationPoint(PointRo point) {
        long loginIdAsLong = StpUtil.getLoginIdAsLong();
        Point chchePoint = new Point(point.getLongitude(), point.getLatitude());
        Long add = redisTemplate.opsForGeo().add(RedisCacheConstants.REDIS_GEO_KEY, chchePoint, loginIdAsLong);
        if(add == 1){
            String format = String.format(RedisCacheConstants.REDIS_GEO_KEY, loginIdAsLong);
            redisTemplate.expire(format,1,TimeUnit.DAYS);
            return JSONResult.success();
        }
        return JSONResult.error();
    }

    @Override
    public JSONResult pullOrderForDriver() {
        long driverId = StpUtil.getLoginIdAsLong();

        return null;
    }


    private void saveUaaLogin(Driver driver) {
        //同步到uaa
        LoginDto loginDto = new LoginDto();
        loginDto.setId(driver.getId());
        loginDto.setPhone(driver.getPhone());
        loginDto.setOpenId(driver.getOpenId());
        loginDto.setType(2);
        loginDto.setUsername(driver.getPhone());
        loginDto.setEnabled(false);
        loginDto.setNickName(NameUtil.getName());
        loginDto.setCreateTime(new Date());
        loginFeignApi.create(loginDto);
    }

    private Driver buildDriver(String openid,String phone) {
        //进行绑定
        Driver driver = new Driver();
        driver.setId(IdUtil.createSnowflake(0L,0L).nextId());
        driver.setOpenId(openid);
        driver.setPhone(phone);
        driver.setCreateTime(new Date());
        driver.setBitState(BitStatesUtils.addState(0, BitStatesUtils.OP_PHONE));
        this.save(driver);
        return driver;
    }
}
